Passed
Push — develop ( 588e30...c592f3 )
by Endre
04:05
created

Router.changePage   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 4.048

Importance

Changes 0
Metric Value
cc 2
eloc 9
dl 0
loc 10
ccs 1
cts 5
cp 0.2
crap 4.048
rs 9.95
c 0
b 0
f 0
1
import {IObserver} from '../Observer/Observer';
2
3
export interface IPageData {
4
  name: string,
5
  url: string,
6
  depth: number
7
}
8
9
export default class Router {
10
  currentPage: IObserver<IPageData>;
11
  history: History;
12
13
  constructor(pageObserver: IObserver<IPageData>, history: History) {
14 1
    this.currentPage = pageObserver;
15 1
    this.history = history;
16
  }
17
18
  attachTo(window: Window) {
19 1
    window.addEventListener('popstate', this.onHistoryChange.bind(this));
20
  }
21
22
  initialize(): void {
23 1
    const firstPage: IPageData = this.currentPage.value;
24 1
    this.history.replaceState(firstPage, firstPage.name, firstPage.url);
25 1
    this.updatePage(firstPage);
26
  }
27
28
  changePage(newPage: IPageData): void {
29
    const currentPage = this.currentPage.value;
30 2
    if (currentPage.name == newPage.name) {
31
      return;
32
    }
33
34
    this.history.replaceState(newPage, newPage.name, newPage.url);
35
36
    this.updatePage(newPage);
37
  }
38
39
  updatePage(page: IPageData): void {
40 1
    this.currentPage.value = page;
41
  }
42
43
  onHistoryChange(event: PopStateEvent) {
44
    const newPage: IPageData = event.state as IPageData;
45
    this.updatePage(newPage);
46
  }
47
}
48